package com.reggie.interceptor;

import com.auth0.jwt.JWT;
import com.reggie.common.enums.front.UserEnum;
import com.reggie.utils.BaseContext;
import com.reggie.utils.JWTUtil;
import com.reggie.utils.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

import static com.reggie.common.Constant.LOGIN_SESSION;


/**
 * @Author 早睡蛋
 * @Date 2022/7/17 17:12:32
 * @Desc:登录拦截器
 */
@Component
@Slf4j
public class BackendInterceptor implements HandlerInterceptor {

    @Resource
    private RedisUtil redisUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        try {
            log.info("进入拦截器方法");
            String token = request.getHeader("token");
            System.out.println(token);
            if (StringUtils.isEmpty(token)) {
                System.out.println("没有token");
                returnJson(response);
                return false;
            }
            Map<String, Object> map = JWTUtil.verifyEmp(token);
            Long id = (Long) map.get("id");
            String empToken = redisUtil.getString(LOGIN_SESSION + id);
            if (empToken == null) {
                returnJson(response);
                return false;
            }
            BaseContext.setCurrentId(id);
            response.setStatus(200);
            return true;
        } catch (Exception e) {
            returnJson(response);
            return false;
        }

    }


    private void returnJson(HttpServletResponse response) {
        PrintWriter writer = null;
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        try {
            writer = response.getWriter();
            UserEnum noLogin = UserEnum.NO_LOGIN;
            writer.print(noLogin.getCode());
        } catch (IOException e) {
            System.out.println(e.getMessage());
        } finally {
            if (writer != null) {
                writer.close();
            }
        }
    }
}
